using System.Collections.Concurrent;
using System.Text;
using CSRedis;

namespace DiLu.Expansion.Redis;

/// <summary>
///     的卢Redis
/// </summary>
public static class DiLuRedis
{
    /// <summary>
    ///     存储多个Redis客户端实例的字典，键为数据库索引，值为延迟初始化的CSRedisClient对象。
    /// </summary>
    private static readonly ConcurrentDictionary<int, Lazy<CSRedisClient>> RedisClients = new();

    /// <summary>
    ///     初始化Redis客户端连接。
    /// </summary>
    /// <param name="config">包含Redis服务器连接信息的配置对象。</param>
    public static void InitializeClient(DiLuRedisConfig config)
    {
        Parallel.For(0, config.DbCount, i =>
        {
            var connectionString = new StringBuilder($"{config.Host}:{config.Port},ssl={config.UseSsl}");
            connectionString.Append($",poolsize={config.PoolSize}");
            if (!string.IsNullOrWhiteSpace(config.Password)) connectionString.Append($",password={config.Password}");
            if (!string.IsNullOrWhiteSpace(config.Prefix)) connectionString.Append($",prefix={config.Prefix}");
            RedisClients.TryAdd(i, new Lazy<CSRedisClient>(() => new CSRedisClient($"{connectionString},defaultDatabase={i}")));
        });
    }

    /// <summary>
    ///     获取指定索引的Redis客户端实例。
    /// </summary>
    /// <param name="index">要获取的Redis数据库的索引。</param>
    /// <returns>与指定索引关联的CSRedisClient实例。</returns>
    public static CSRedisClient GetClient(int index)
    {
        return RedisClients[index].Value;
    }
}